package ua.ad.feedsreader.actions;

import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.struts2.interceptor.SessionAware;

import ua.ad.feedsreader.mybatis.config.MyBatisSqlSessionFactory;

import com.opensymphony.xwork2.ActionSupport;
import ua.ad.feedsreader.mybatis.mappers.beans.Utilizador;
import ua.ad.feedsreader.mybatis.mappers.beans.UtilizadorAcesso;
import ua.ad.feedsreader.mybatis.mappers.clients.UtilizadorAcessoMapper;
import ua.ad.feedsreader.mybatis.mappers.clients.UtilizadorMapper;

public class LoginAction extends ActionSupport implements SessionAware {

    /**
     * 
     */
    private static final long serialVersionUID = -8195916028183163494L;
    private Map<String, Object> session;
    private String errorMessage;
    private Utilizador user;
    private String username;
    private String password;

    @Override
    public String execute() throws Exception {

        SqlSession bdSession = MyBatisSqlSessionFactory.getSqlSessionFactory().openSession();

        UtilizadorAcessoMapper userAccessMapper = bdSession.getMapper(UtilizadorAcessoMapper.class);
        UtilizadorAcesso useraccess = userAccessMapper.selectByNickAndPassword(username, password);

        if (useraccess != null) {

            UtilizadorMapper userInfoMapper = bdSession.getMapper(UtilizadorMapper.class);
            setUser(userInfoMapper.selectByPrimaryKey(useraccess.getIdUser()));
            getSession().put("utilizador", getUser());

            bdSession.close();
            return SUCCESS;
        }

        bdSession.close();

        setErrorMessage("Login ou Password errada!");

        return ERROR;
    }

    /**
     * @return the errorMessage
     */
    public String getErrorMessage() {
        return errorMessage;
    }

    /**
     * @param errorMessage the errorMessage to set
     */
    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    public Map<String, Object> getSession() {
        return session;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the user
     */
    public Utilizador getUser() {
        return user;
    }

    /**
     * @param user the user to set
     */
    public void setUser(Utilizador user) {
        this.user = user;
    }
}
